package com.edu.zut.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.zut.domain.LoginUser;
import com.edu.zut.entity.User;
import com.edu.zut.mapper.RoleMapper;
import com.edu.zut.mapper.UserMapper;
import com.edu.zut.mapper.UserRoleMapper;
import com.edu.zut.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 许文科
 * @Date 2023/1/12 20:06
 * @Description paperdetect-bcak
 * <p>
 * 重写登录过程中的身份认证流程，查询数据库获得登录人信息
 */
@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查找该用户的信息
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        User user = userMapper.selectOne(wrapper);

        //权限集合
        List<Long> roleIds = userRoleMapper.selectRoleIdsByUserId(user.getUserId());

        List<String> roleNames = roleMapper.selectRoleNameByRoleIds(roleIds);

        return new LoginUser(user, roleNames);
    }
}
